package member

import (
	"fmt"
	"github.com/gin-gonic/gin"
	memberForms "shopstar/forms/api/member"
	"shopstar/global"
	"shopstar/reponse"
	memberResponse "shopstar/reponse/member"
	"shopstar/util"
)

func Login(ctx *gin.Context) {
	req := new(memberForms.Login)
	if err := ctx.ShouldBind(req); err != nil {
		reponse.FailWithMsg("登录失败", ctx)
		return
	}
	fmt.Println(req)
	model, err := memberService.Login(req.Username, req.Password)
	if err != nil {
		reponse.FailWithErr(err, ctx)
		return
	}
	token, _ := util.JWT.GenerateToken(global.JwtKey, map[string]interface{}{
		"member_id": model.Id,
	})
	reponse.OKWithDatailed(gin.H{
		"token": token,
	}, "登录成功", ctx)
}

func Register(ctx *gin.Context) {
	req := new(memberForms.Register)
	if err := ctx.ShouldBind(req); err != nil {
		reponse.FailWithErr(global.ErrRegister, ctx)
		return
	}
	_, err := memberService.Register(req.Username, req.Password, req.Phone)
	if err != nil {
		reponse.FailWithErr(err, ctx)
		return
	}
	reponse.OKWithMsg("注册成功", ctx)
}

// GetMember 查询
func GetMember(ctx *gin.Context) {
	req := new(memberForms.GetMember)
	if err := ctx.ShouldBind(req); err != nil {
		reponse.FailWithErr(global.ErrGormRecordNotFound, ctx)
		return
	}
	fmt.Println(req)
	model, err := memberService.FindMemberUsername(req.Username)
	if err != nil {
		reponse.FailWithErr(global.ErrGormRecordNotFound, ctx)
		return
	}
	reponse.OKWithData(model, ctx)
}

// 查询默认收货地址
func DefaultAddress(ctx *gin.Context) {
	id := ctx.Query("user_id")
	address, _ := memberService.DefaultMemberAddress(id)
	province, city, district := areaService.GetAddress(address.ProvinceId, address.CityId, address.DistrictId)
	reponse.OKWithData(&memberResponse.MemberAddress{
		Address:  address,
		Province: province.ProvinceName,
		City:     city.CityName,
		District: district.DistrictName,
	}, ctx)
}
